<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>RRID DEVICE TEST PAGE</title>
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">

      <div class="btn-group-vertical w-100">
        <button id="open-device-btn" class="btn btn-primary mt-3">Open Device</button>
        <button id="close-device-btn" class="btn btn-danger mt-3">Close Device</button>
        <button id="device-info-btn" class="btn btn-info mt-3">Get Device Info</button>
        <button id="device-success-btn" class="btn btn-success mt-3">Get Tags Info</button>
        <button id="poll-tags-btn" class="btn btn-warning mt-3">Start Polling Tags</button>
        
        <div class="mt-3 w-100 border rounded">
          <table class="table w-100">
            <tr>
              <td class="pe-3" width="33%"><label for="uid-select" class="form-label">UID</label></td>
              <td>
                <select class="form-select" id="uid-select">
                  <option value="">Select UID</option>
                </select>
              </td>
            </tr>
            <tr>
              <td class="pe-3"><label for="block-start" class="form-label">Block Start</label></td>
              <td>
                <select class="form-select" id="block-start">
                  <option value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                  <option value="17">17</option>
                  <option value="18">18</option>
                  <option value="19">19</option>
                  <option value="20">20</option>
                  <option value="21">21</option>
                  <option value="22">22</option>
                  <option value="23">23</option>
                  <option value="24">24</option>
                  <option value="25">25</option>
                  <option value="26">26</option>
                  <option value="27">27</option>
                </select>
              </td>
            </tr>
            <tr>
              <td class="pe-3"><label for="block-count" class="form-label">Block Count</label></td>
              <td>
                <select class="form-select" id="block-count">
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                  <option value="17">17</option>
                  <option value="18">18</option>
                  <option value="19">19</option>
                  <option value="20">20</option>
                  <option value="21">21</option>
                  <option value="22">22</option>
                  <option value="23">23</option>
                  <option value="24">24</option>
                  <option value="25">25</option>
                  <option value="26">26</option>
                  <option value="27">27</option>
                  <option value="28">28</option>
                </select>
              </td>
            </tr>
            <tr>
              <td class="pe-3"><label for="tag-data" class="form-label">Tag Data (Hex)</label></td>
              <td>
                <input type="text" class="form-control" id="tag-data" placeholder="Enter tag data">
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <button id="read-btn" class="btn btn-success">Read Block</button>
                <button id="write-btn" class="btn btn-primary">Write Block</button>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <button id="open-eas-btn" class="btn btn-primary">Open EAS</button>
                <button id="close-eas-btn" class="btn btn-primary">Close EAS</button>
                <button id="get-eas-status-btn" class="btn btn-success">Get EAS Status</button>
              </td>
            </tr>
            <tr>
              <td>
                <button id="write-afi-btn" class="btn btn-primary">Write AFI</button>
                <button id="get-tag-status-btn" class="btn btn-success">Get Tag Status</button>
              </td>
              <td>
                <input type="text" class="form-control" id="afi-data" placeholder="AFI (Hex)">
              </td>

            </tr>

          </table>
        </div>
      </div>
      
      <div id="device-info-result" class="mt-3"></div>
      <div id="tags-table" class="mt-3" style="display: none;">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>UID</th>
              <th>Antenna</th>
              <th>RSSI</th>
              <th>Type</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
    <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    <script>
      $(document).ready(function() {
        function handleAjax(url, successMessage, isTags=false) {
          $.ajax({
            url: url,
            method: 'POST',
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
                $('#tags-table').hide();
              } else {
                if (isTags) {
                  // Clear existing options and add default
                  $('#uid-select').empty().append('<option value="">Select UID</option>');
                  
                  // Clear table
                  $('#tags-table tbody').empty();
                  
                  response.tags.forEach(tag => {
                    // Add UID to select dropdown
                    $('#uid-select').append(
                      `<option value="${tag.UID}">${tag.UID}</option>`
                    );
                    
                    // Add tag to table
                    $('#tags-table tbody').append(
                        `<tr>
                          <td>${tag.UID}</td>
                          <td>${tag.AntId}</td>
                          <td>${tag.RSSI}</td>
                          <td>${tag.TagType}</td>
                        </tr>`
                    );
                  });
                  $('#tags-table').show();
                  $('#device-info-result').html(
                    `<div class="alert alert-success">Found ${response.tags.length} tags</div>`
                  );
                } else {
                  $('#device-info-result').html(
                    '<div class="alert alert-success">' + response.message + '</div>'
                  );
                  $('#tags-table').hide();
                }
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Request failed</div>'
              );
              $('#tags-table').hide();
            }
          });
        }

        $('#open-device-btn').click(function() {
          handleAjax('/open-device', 'Device opened successfully');
        });

        $('#device-info-btn').click(function() {
          handleAjax('/device-info', 'Device info retrieved');
        });

        $('#close-device-btn').click(function() {
          handleAjax('/close-device', 'Device closed successfully');
        });

        // Polling state and interval
        let isPolling = false;
        let pollInterval = null;
        
        $('#poll-tags-btn').click(function() {
          if (isPolling) {
            // Stop polling
            clearInterval(pollInterval);
            isPolling = false;
            $(this).removeClass('btn-danger').addClass('btn-warning')
                   .text('Start Polling Tags');
            $('#device-info-result').html(
              '<div class="alert alert-info">Polling stopped</div>'
            );
          } else {
            // Start polling
            isPolling = true;
            $(this).removeClass('btn-warning').addClass('btn-danger')
                   .text('Stop Polling Tags');
            // Initial fetch
            handleAjax('/get-tags-info', '', true);
            // Set up interval
            pollInterval = setInterval(function() {
              handleAjax('/get-tags-info', '', true);
            }, 1500);
          }
        });

        $('#device-success-btn').click(function() {
          handleAjax('/get-tags-info', '', true);
        });

        $('#read-btn').click(function() {
          const blockStart = $('#block-start').val();
          const blockCount = $('#block-count').val();
          
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/read-tag',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              uid: uid,
              blockStart: blockStart,
              blockCount: blockCount
            }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#tag-data').val(response.data);
                $('#device-info-result').html(
                  '<div class="alert alert-success">Tag data read successfully</div>'
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to read tag data</div>'
              );
            }
          });
        });

        $('#write-btn').click(function() {
          const blockStart = $('#block-start').val();
          const blockCount = $('#block-count').val();
          const tagData = $('#tag-data').val();
          
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          if (!tagData) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please enter tag data</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/write-tag',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              uid: uid,
              blockStart: blockStart,
              blockCount: blockCount,
              tagData: tagData
            }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#device-info-result').html(
                  '<div class="alert alert-success">' + response.message + '</div>'
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to write tag data</div>'
              );
            }
          });
        });

        // EAS Button Handlers
        $('#open-eas-btn').click(function() {
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/enable-eas',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ uid: uid }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#device-info-result').html(
                  '<div class="alert alert-success">' + response.message + '</div>'
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to enable EAS</div>'
              );
            }
          });
        });

        $('#close-eas-btn').click(function() {
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/disable-eas',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ uid: uid }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#device-info-result').html(
                  '<div class="alert alert-success">' + response.message + '</div>'
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to disable EAS</div>'
              );
            }
          });
        });

        $('#get-eas-status-btn').click(function() {
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/check-eas',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ uid: uid }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                const statusText = response.status === 1 ? 'Enabled' : 'Disabled';
                $('#device-info-result').html(
                  `<div class="alert alert-success">
                    ${response.message}<br>
                    EAS Status: ${statusText}
                  </div>`
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to check EAS status</div>'
              );
            }
          });
        });

        // AFI Button Handlers
        $('#write-afi-btn').click(function() {
          const uid = $('#uid-select').val();
          const afi = $('#afi-data').val();
          
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          if (!afi || !/^[0-9a-fA-F]{2}$/.test(afi)) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please enter a valid 2-digit hex AFI value</div>'
            );
            return;
          }
          
          const afiValue = parseInt(afi, 16);
          
          $.ajax({
            url: '/write-afi',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ 
              uid: uid,
              afi: afiValue
            }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#device-info-result').html(
                  '<div class="alert alert-success">' + response.message + '</div>'
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to write AFI</div>'
              );
            }
          });
        });

        $('#get-tag-status-btn').click(function() {
          const uid = $('#uid-select').val();
          if (!uid) {
            $('#device-info-result').html(
              '<div class="alert alert-danger">Please select a UID</div>'
            );
            return;
          }
          
          $.ajax({
            url: '/get-tag-status',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ uid: uid }),
            success: function(response) {
              if (response.error) {
                $('#device-info-result').html(
                  '<div class="alert alert-danger">' + response.message + '</div>'
                );
              } else {
                $('#device-info-result').html(
                  `<div class="alert alert-success">
                    ${response.message}<br>
                    DSFID: ${response.status.dsfid.toString(16)}<br>
                    AFI: ${response.status.afi.toString(16)}<br>
                    Block Size: ${response.status.block_size}<br>
                    Block Count: ${response.status.block_count}<br>
                    IC Reference: ${response.status.ic_ref.toString(16)}
                  </div>`
                );
              }
            },
            error: function() {
              $('#device-info-result').html(
                '<div class="alert alert-danger">Failed to get tag status</div>'
              );
            }
          });
        });
      });
    </script>
    
  </body>
</html>
